﻿using System.Net;
using System.Text;
using Furion.DynamicApiController;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using 微信信息管理系统.Code.Model;

namespace 微信信息管理系统.Code.Service;

public class MpService : IDynamicApiController
{
    private readonly IFreeSql _fsql;

    public MpService(IFreeSql fsql)
    {
        _fsql = fsql;
    }

    public object GetWxInfo(string code)
    {
        // 获取微信用户信息
        var url = $"http://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1d304af4b2f2c6f8&secret=fa26b7383f8d667b13d2b7f05eecf6c9&code={code}&grant_type=authorization_code";
        var wxInfo = HttpHelper.Get(url);
        var wxInfoJson = JsonConvert.DeserializeObject<WxInfo>(wxInfo);
        var userInfo = HttpHelper.Get($"https://api.weixin.qq.com/sns/userinfo?access_token={wxInfoJson.access_token}&openid={wxInfoJson.openid}&lang=zh_CN");

        var userInfoJson = JsonConvert.DeserializeObject<WxUserInfo>(userInfo);
        // 查询用户是否存在
        var user = _fsql.Select<User>().Where(x => x.OpenId == userInfoJson.openid).ToOne();
        if (user == null)
        {
            return userInfoJson;
        }

        return user.Adapt<UserResDto>();
    }
}

public class WxUserInfo
{
    public string openid { get; set; }
    public string nickname { get; set; }
    public string headimgurl { get; set; }
}

public class WxInfo
{
    public string access_token { get; set; }
    public string expires_in { get; set; }
    public string refresh_token { get; set; }
    public string openid { get; set; }
    public string scope { get; set; }
}

public class HttpHelper
{
    public static string Get(string url)
    {
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "text/html;charset=UTF-8";
        HttpWebResponse response = (HttpWebResponse) request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();
        return retString;
    }
}